<script setup lang="ts">
import { useWebxRouteTabs, useWebxTable } from "@webxue/vue3-antdv-ui";
import { CheckOutlined } from "@ant-design/icons-vue";
import { reactive } from "vue";
import { BaseApi } from "@/apis/base.api";
import { message } from "ant-design-vue";
import { useUserStore } from "@/stores/user.store";
import { UtilTool } from "@webxue/common";
import useUser from "@/hooks/useUser";
import useCusRouter from "@/hooks/useCusRouter";

const { router } = useCusRouter();
const { addTab } = useWebxRouteTabs({ router });
const { searchForm, dataSource, columns, pagination, doRefresh, doSearch, doReset, doCreate, doUpdate, doDelete } = useWebxTable({
  searchForm:{
    name:""
  },
  tableColumns:[
    { title: "序号", dataIndex: "index", align: "center", width: 50 },
    { title: "昵称", dataIndex: "user.nickName", width: 100 },
    { title: "状态", dataIndex: "status", width: 100 },
    { title: "状态描述", dataIndex: "statusMsg" },
    { title: "备注", dataIndex: "remark" },
    { title: "操作", dataIndex: "operate", width: 180 }
  ],
  async api(params){
    const response = await BaseApi.developer.list({
      page: params.page,
      size: params.size
    });
    return Promise.resolve(response.data);
  },
  // 新增
  async onCreate() {
    addTab({
      title: "新增开发者",
      href: "/developer/form",
      key: "create-developer",
    })
  },
  // 编辑
  async onUpdate(record) {
    addTab({
      title: "编辑开发者-" + record.user.nickName,
      href: "/developer/form?developerId=" + record.id,
      key: "edit-developer" + record.id,
    })
  },
  // 删除
  async onDelete(record) {
    const response = await BaseApi.developer.delete({ ids: record.id });
    if(response.success) {
      await useUser().refresh();
      message.success("取消开发者权限成功");
      await doSearch();
    }
  }
});
// 审核
const approveModal = reactive({
  open: false,
  title: "权限审核",
  formState:{} as Record<string, any>,
  // 修改状态时快捷填入状态描述
  onChangeStatus(){
    if(approveModal.formState.status === 1) {
      approveModal.formState.statusMsg = "恭喜您，开发者权限申请成功！";
    } else if(approveModal.formState.status === 2) {
      approveModal.formState.statusMsg = "很抱歉，您的开发者权限暂时被停用，请联系管理员恢复";
    } else if(approveModal.formState.status === 5) {
      approveModal.formState.statusMsg = "您的开发者权限正在审核中，请耐心等待";
    }
  },
  async onOk(){
    const response = await BaseApi.developer.updateStatus({
      ids:approveModal.formState.id,
      status:approveModal.formState.status,
      statusMsg:approveModal.formState.statusMsg
    });
    if(response.success) {
      message.success(response.message || "保存成功");
      approveModal.open = false;
      await doSearch();
      await useUser().refresh();
    }
  },
  // 审核
  onApprove(record:any){
    approveModal.formState = UtilTool.lodash.cloneDeep(record);
    approveModal.open = true;
  }
});

// 查看开发者应用
function viewDevApp(developer:any){
  addTab({
    key:"view-devApp-" + developer.id,
    title:"查看开发者应用-" + developer.user.nickName,
    href: `/devApp/index?nickName=${developer.user.nickName}&developerId=${developer.id}`
  })
}
</script>

<template>
  <div class="person-index flex flex-col gap-2">
    <!-- 查询条件 -->
    <WebxSearch
      :model="searchForm"
      @submit="doSearch"
      @reset="doReset"
    >
      <AFormItem label="关键词">
        <AInput v-model:value="searchForm.name" placeholder="请输入关键词" />
      </AFormItem>
    </WebxSearch>
    <!-- 表格 -->
    <WebxTable
      :dataSource="dataSource"
      :columns="columns"
      :pagination="pagination"
      :showCreate="false"
      @refresh="doRefresh"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'index'">{{ index + 1 }}</template>
        <template v-if="column.dataIndex === 'status'">
          <ATag color="orange" v-if="record.status === 5">审核中</ATag>
          <ATag color="green" v-else-if="record.status === 1">已通过</ATag>
          <ATag color="red" v-else>已拒绝</ATag>
        </template>
        <template v-if="column.dataIndex === 'operate'">
          <div class="flex gap-2">
            <WebxBtn v-if="record.status === 1" btnText="权限移除" operate="del" :modalContant="`确定要移除 ${record.user.nickName} 的开发者权限吗？`"
                     @delete="() => doDelete(record)" />
            <WebxBtn v-if="record.status !== 1 && useUserStore().hasPermission('developer:audit')" btnText="审核" operate="edit" @click="approveModal.onApprove(record)" />
            <WebxBtn operate="on" btnText="查看应用" @click="viewDevApp(record)" />
          </div>
        </template>
      </template>
    </WebxTable>

    <!-- 权限审核 -->
    <AModal v-model:open="approveModal.open" :title="approveModal.title" :footer="null">
      <AForm :model="approveModal.formState" @finish="approveModal.onOk">
        <AFormItem name="status" :rules="[{ required:true, message:'请选择状态' }]">
          <ARadioGroup v-model:value="approveModal.formState.status" @change="approveModal.onChangeStatus">
            <ARadio :value="1">正常</ARadio>
            <ARadio :value="2">停用</ARadio>
            <ARadio :value="5">审核中</ARadio>
          </ARadioGroup>
        </AFormItem>
        <AFormItem label="状态描述" name="statusMsg" :rules="[{ required:true, message:'请填写原因' }]">
          <ATextarea v-model:value="approveModal.formState.statusMsg" placeholder="请填写原因" :autoSize="{ minRows:2, maxRows:2 }" />
        </AFormItem>
        <AFormItem>
          <div class="flex justify-end">
            <AButton type="primary" htmlType="submit"><CheckOutlined /> 保存</AButton>
          </div>
        </AFormItem>
      </AForm>
    </AModal>
  </div>
</template>

<style scoped lang="less"></style>
